Graficación en ggplot2 y quarto

Introducción

Este documento presenta un conjunto visualizaciones de datos elaborados de datos elaborados con paquetes del lenguaje R como ggplot, plotly y DT

#Carga de bibliotecas

library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.2     ✔ readr     2.1.4
✔ forcats   1.0.0     ✔ stringr   1.5.0
✔ ggplot2   3.4.2     ✔ tibble    3.2.1
✔ lubridate 1.9.2     ✔ tidyr     1.3.0
✔ purrr     1.0.1     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(plotly)

Attaching package: 'plotly'

The following object is masked from 'package:ggplot2':

    last_plot

The following object is masked from 'package:stats':

    filter

The following object is masked from 'package:graphics':

    layout
library(DT)
library(gapminder)
library(palmerpenguins)
library(ggthemes)
library(hrbrthemes)
NOTE: Either Arial Narrow or Roboto Condensed fonts are required to use these themes.
      Please use hrbrthemes::import_roboto_condensed() to install Roboto Condensed and
      if Arial Narrow is not on your system, please see https://bit.ly/arialnarrow

#carga de datos

#| label: carga-datos-mpg
#| warning: false
#| code-fold: true
mpg |>
  datatable()
    options = list(
      pageLength = 5,
      language = list(url = '//cdn.datatables.net/plug-ins/1.10.11/i18n/Spanish.json')
    )

diamons

#| label: carga-datos-diamonds
#| warning: false
#| code-fold: true
diamonds |>
  datatable()
Warning in instance$preRenderHook(instance): It seems your data is too big for
client-side DataTables. You may consider server-side processing:
https://rstudio.github.io/DT/server.html
    options = list(
      pageLength = 5,
      language = list(url = '//cdn.datatables.net/plug-ins/1.10.11/i18n/Spanish.json')
    )

##gapminder

#| label: carga-datos-gapminder
#| warning: false
#| code-fold: true
gapminder |>
  filter(year == 2007) |>
  datatable()
    options = list(
      pageLength = 5,
      language = list(url = '//cdn.datatables.net/plug-ins/1.10.11/i18n/Spanish.json')
    )

COVID

Código
# Carga del archivo CSV de entrada en un dataframe
# con la función read_delim() de readr
covid_general <-
  read_delim(
    file = "https://raw.githubusercontent.com/gf0604-procesamientodatosgeograficos/2023-i/main/datos/ministerio-salud/covid/05_30_22_CSV_GENERAL.csv",
    col_select = c(
      "FECHA",
      "positivos",
      "activos",
      "RECUPERADOS",
      "fallecidos",
      "nue_posi",
      "nue_falleci",
      "salon",
      "UCI"
    )
  )

# Cambio de nombre de columnas
covid_general <-
  covid_general |>
  rename(
    fecha = FECHA,
    recuperados = RECUPERADOS,
    nuevos_positivos = nue_posi,
    nuevos_fallecidos = nue_falleci,
    uci = UCI
  )

# Cambio de tipo de datos de la columna fecha, de str a date
covid_general <-
  covid_general |>
  mutate(fecha = as.Date(fecha, format = "%d/%m/%Y"))

# Despliegue de datos
covid_general |>
  datatable()
Código
    options = list(
      pageLength = 5,
      language = list(url = '//cdn.datatables.net/plug-ins/1.10.11/i18n/Spanish.json')
    )

Delitos

Código
# Carga de datos
delitos_2022 <-
  read_delim(
    file = "https://raw.githubusercontent.com/gf0604-procesamientodatosgeograficos/2023-i/main/datos/oij/estadisticas-policiales/estadisticaspoliciales2022.csv"
  )

# Tabla de datos
delitos_2022 |>
  datatable(
    options = list(
      pageLength = 5,
      language = list(url = '//cdn.datatables.net/plug-ins/1.10.11/i18n/Spanish.json')
    )
  )

Operaciones básicas de ggplor2

# Forma básica
ggplot(data = mpg) +
  geom_point(mapping = aes (x = displ, y = hwy))

variables adicionales

# class - color
mpg |>
  ggplot(aes(x = displ, y = hwy, shape = class)) +
  geom_point()
Warning: The shape palette can deal with a maximum of 6 discrete values because
more than 6 becomes difficult to discriminate; you have 7. Consider
specifying shapes manually if you must have them.
Warning: Removed 62 rows containing missing values (`geom_point()`).

mpg |>
  ggplot(aes(x = displ, y = hwy, color = class)) +
  geom_point()

# Gráfico de dispersión de cilindrada vs millas por galón en autopista
# con formas y colores correspondientes al tipo de automóvil
mpg |>
  ggplot(aes(x = displ, y = hwy, shape = class, color = class)) +
  geom_point() +
  scale_shape_manual(values = c(0, 1, 2, 3, 4, 5, 6)) +
  scale_color_manual(values = c("red", "blue", "green", "purple", "orange", "brown", "pink"))

mpg |>
  ggplot(aes(x = hwy, y = cty, size = displ)) +
  geom_point()

Operaciones basicas de ggplot2

De acuerdo con la “Gramatica de los graficos”, todo grafico estadistico tiene tres componentes:

  1. Datos (data frame)
  2. Mapeos de las columnas del dataframe a las propiedades visuales del grafico (x, y, color, tamaño, forma, etc.)
  3. Una o varias apas con geometrias (geom_point(), geo_bar(), geo_bax().)
Código
mpg |>
  ggplot(aes(x = displ, y = hwy)) +
  geom_point()

Cargue el conjunto de datos de penguins y genere un grafico de dispersion que muestre la relacion: peso vs longitud de la aleta

Código
penguins |>
  ggplot(aes(x = body_mass_g, y = flipper_length_mm)) +
  geom_point()

Código
mpg |>
  ggplot(aes(x = displ, y = hwy, color = class)) +
  geom_point()

Código
mpg |>
  ggplot(aes(x = displ, y = hwy, shape = class)) +
  geom_point()

Código
mpg |>
  ggplot(aes(x = displ, y = hwy, shape = class, color = class)) +
  geom_point() +
  scale_shape_manual(values = c(0, 1, 2, 3, 4, 5, 6)) +
  scale_color_manual(values = c("red", "blue", "green", "purple", "orange", "brown", "pink"))

capas adicionales

Código
mpg |>
  ggplot(aes(x = displ, y = hwy, color = class)) +
  geom_point() +
  geom_smooth(method = "lm")

#pinguinos peso vs longitud de aleta, colores segun especie y linea de tendencia.

Código
penguins |>
  ggplot(aes(x = body_mass_g, y = flipper_length_mm, color = species,)) +
  geom_point() +
   geom_smooth(method = "lm")

Paneles (facets)

mpg |>
  ggplot(aes(x = displ, y = hwy)) +
  geom_point() +
  facet_wrap(~ class, ncol = 2)

Genere un arreglo de paneles que muestre en cada panel la relación entre peso y longitud de la aleta para cada especie.

Código
penguins |>
  ggplot(aes(x = body_mass_g, y = flipper_length_mm, color = species)) +
  geom_point() +
  facet_wrap(~ species)

Genere graficos de dispersión en paneles para cada continente que muestre la relación entre el PIB per capita (x) y la esperanza de vida (y)

Código
gapminder |>
  filter(year == 2007)|>
  ggplot(aes(x = gdpPercap, y = lifeExp, )) +
  geom_point() +
  facet_wrap(~ continent)

Código
gapminder |>
  filter(year == 2007)|>
  ggplot(aes(x = gdpPercap, y = lifeExp, )) +
  geom_point() +
  geom_smooth()

Gráfico de dispersión de cilindrada vs millas por galón en autopista

+ paneles por tipo de automóvil y tipo de tracción

Código
mpg |>
  ggplot(aes(x = displ, y = hwy)) +
  geom_point() +
  facet_grid(class ~ drv)

Gráfico de dispersión de cilindrada vs millas por galón en autopista

coloreado por tipo de tracción con título, subtítulo y etiquetas

mpg |>
  ggplot(aes(x = displ, y = hwy, color = drv)) +
  geom_point() +
  geom_smooth() +
  ggtitle("Cilindrada vs rendimiento en autopista por tipo de tracción") +
  xlab("Cilindrada (l)") +
  ylab("Rendimiento en autopista (mpg)") +
  labs(subtitle = "Datos de 38 modelos de automóviles de años entre 1999 y 2008", 
       caption = "Fuente: United States Environmental Protection Agency (EPA)",
       color = "Tipo de tracción") +
  theme_ft_rc()

Gráfico de dispersión de peso vs precio de diamantes

coloreado por claridad

diamonds |>
  ggplot(aes(x = carat, y = price, color = clarity)) +
  geom_point() +
  ggtitle("Peso vs precio de diamantes") +
  xlab("Peso (quilates)") +
  ylab("Precio ($ EE.UU.)") +
  labs(color = "Claridad\n(I1=peor IF=mejor)") +
  scale_colour_brewer(palette = "PuBu", direction = -1) +
  theme_ipsum() # estilo de hrbrthemes
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
not found in Windows font database

Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
not found in Windows font database
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : font
family not found in Windows font database
Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
not found in Windows font database

Warning in grid.Call(C_stringMetric, as.graphicsAnnot(x$label)): font family
not found in Windows font database
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : font
family not found in Windows font database

Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : font
family not found in Windows font database

Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : font
family not found in Windows font database

Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : font
family not found in Windows font database

Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : font
family not found in Windows font database

Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : font
family not found in Windows font database

Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : font
family not found in Windows font database

Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : font
family not found in Windows font database

Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : font
family not found in Windows font database

Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : font
family not found in Windows font database
Warning in grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y, :
font family not found in Windows font database
Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : font
family not found in Windows font database

Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : font
family not found in Windows font database

Warning in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : font
family not found in Windows font database

##plotly

grafico_ggplot2 <-
  mpg |>
  ggplot(aes(x = displ, y = hwy, color = drv)) +
  geom_point(aes(
    # datos que se muestran al colocar el ratón sobre un punto
    text = paste0(
      "Modelo: ", manufacturer, " ", model, " ", year, "\n",
      "Cilindrada: ", displ, " l", "\n",
      "Rendimiento en autopista: ", hwy, " mpg", "\n",
      "Tipo de tracción: ", drv
    )
  )) +
  geom_smooth() +
  ggtitle("Cilindrada vs rendimiento en autopista") +
  xlab("Cilindrada (l)") +
  ylab("Rendimiento en autopista (mpg)") +
  labs(subtitle = "Datos de 38 modelos de automóviles de años entre 1999 y 2008",
       caption = "Fuente: United States Environmental Protection Agency (EPA)",
       color = "Tipo de tracción") +
  theme_ipsum()
diamonds |>
  ggplot(aes(x = carat, y = price, color = clarity)) +
  geom_point() +
  ggtitle("Peso vs precio de diamantes") +
  xlab("Peso (quilates)") +
  ylab("Precio ($ EE.UU.)") +
  labs(color = "Claridad\n(I1=peor IF=mejor)") +
  scale_colour_brewer(palette = "YlOrBr", direction = -1) +
  theme_ipsum() # estilo de hrbrthemes

# Gráfico ggplot2
grafico_ggplot2 <-
  mpg |>
  ggplot(aes(x = displ, y = hwy, color = drv)) +
  geom_point(aes(
    # datos que se muestran al colocar el ratón sobre un punto
    text = paste0(
      "Modelo: ", manufacturer, " ", model, " ", year, "\n",
      "Cilindrada: ", displ, " l", "\n",
      "Rendimiento en autopista: ", hwy, " mpg", "\n",
      "Tipo de tracción: ", drv, "\n",
      "Tipo de transmisión: ", trans
    )
  )) +
  geom_smooth() +
  ggtitle("Cilindrada vs rendimiento en autopista") +
  xlab("Cilindrada (l)") +
  ylab("Rendimiento en autopista (mpg)") +
  labs(subtitle = "Datos de 38 modelos de automóviles de años entre 1999 y 2008",
       caption = "Fuente: United States Environmental Protection Agency (EPA)",
       color = "Tipo de tracción") +
  theme_ipsum()

# Gráfico plotly
ggplotly(grafico_ggplot2, tooltip = "text") |> 
  config(locale = 'es') # para mostrar los controles en español
#|label: histograma
#|wwarning: false

# Histograma ggplot2 de distribución del PIB per cápita en 2007
histograma_ggplot2 <-
  gapminder |>
  filter(year == 2007) |>
  ggplot(aes(x = gdpPercap)) +
  geom_histogram(
    aes(
      text = paste0(
        "PIB per cápita (valor medio del rango): $", round(after_stat(x), 2), "\n",
        "Frecuencia: ", after_stat(count)
      ),
      y = after_stat(density) # argumento necesario para crear la curva KDE
    ),
    bins = 10
  ) +
  geom_density() +
  scale_y_continuous(labels = scales::label_comma()) + # para formatear el eje y en notación decimal
  ggtitle("Distribución del PIB per cápita en 2007") +
  xlab("PIB per cápita ($ EE.UU.)") +
  ylab("Densidad") +
  labs(subtitle = "Datos de 140 países", caption = "Fuente: Gapminder.org") +
  theme_economist()
Warning in geom_histogram(aes(text = paste0("PIB per cápita (valor medio del
rango): $", : Ignoring unknown aesthetics: text
# Histograma plotly
ggplotly(histograma_ggplot2, tooltip = "text") |>
  config(locale = 'es')
#|label: colores-pobresa
#|wwarning: 
# Histograma ggplot2 de distribución del PIB per cápita en 2007 por continente
histograma_ggplot2 <-
  gapminder |>
  filter(year == 2007) |>
  ggplot(aes(x = gdpPercap, fill = continent)) +
  geom_histogram(
    aes(
      text = paste0(
        "Continente: ", after_stat(fill), "\n",
        "PIB per cápita (valor medio del rango): $", round(after_stat(x), 2), "\n",
        "Frecuencia: ", after_stat(count)
      ),      
      y = after_stat(density)
    ),    
    bins = 10
  ) +
  ggtitle("Distribución del PIB per cápita en 2007 por continente") +
  xlab("PIB per cápita ($ EE.UU.)") +
  ylab("Densidad") +
  labs(subtitle = "Datos de 140 países",
       caption = "Fuente: Gapminder.org",
       fill = "Continente") +
  theme_economist()
Warning in geom_histogram(aes(text = paste0("Continente: ", after_stat(fill), :
Ignoring unknown aesthetics: text
# Histograma plotly
ggplotly(histograma_ggplot2, tooltip = "text") |>
  config(locale = 'es')
# Histogramas ggplot2 de distribución del PIB per cápita en 2007 por continente
histograma_ggplot2 <-
  gapminder |>
  filter(year == 2007) |>
  ggplot(aes(x = gdpPercap)) +
  geom_histogram(
    aes(
      text = paste0(
        "PIB per cápita (valor medio del rango): $", round(after_stat(x), 2), "\n",
        "Frecuencia: ", after_stat(count)
      )
    ),
    bins = 10
  ) +
  ggtitle("Distribución del PIB per cápita en 2007 por continente") +
  xlab("PIB per cápita ($ EE.UU.)") +
  ylab("Frecuencia") +
  labs(subtitle = "Datos de 140 países",
       caption = "Fuente: Gapminder.org",
       fill = "Continente") +
  facet_wrap(~ continent, nrow = 2) +
  theme_economist()

# Histograma plotly
ggplotly(histograma_ggplot2, tooltip = "text") |>
  config(locale = 'es')

Graficos de caja

boxplot_ggplot2 <-
gapminder |>
  filter(year == 2007) |>
  ggplot(aes(x= continent,y = gdpPercap)) +
  geom_boxplot()
ggplotly(boxplot_ggplot2) |>
  config(locale = "es")

Graficos de barras

grafico_barras_ggplot2 <-
gapminder |>
  filter(year == 2007) |>
  ggplot(aes(x = fct_infreq(continent))) +
  geom_bar()
ggplotly(grafico_barras_ggplot2)

diamantes

diamonds |>
  ggplot(aes(x = cut))+
geom_bar()

#Grafico de barras

##Transformaciones estadisticas

grafico_ggplot2 <-
gapminder |>
  filter(year == 2007) |>
  ggplot(aes(x = fct_infreq(continent), y = lifeExp)) +
  geom_bar(
    stat = "summary",
    fun.y = "mean",
     aes(
      text = paste0(
        "Esperanza de vida: ", after_stat(count)
      )
    ), 
    
   ) +
  ggtitle("Promedio de esperanza de vida por continente") +
  xlab("Continente") +
  ylab("Promedio de esperanza de vida") +
  labs(caption = "Fuente: Gapminder.org") +
  theme_economist()
Warning in geom_bar(stat = "summary", fun.y = "mean", aes(text =
paste0("Esperanza de vida: ", : Ignoring unknown parameters: `fun.y`
Warning in geom_bar(stat = "summary", fun.y = "mean", aes(text =
paste0("Esperanza de vida: ", : Ignoring unknown aesthetics: text

##sin transformciones estadisticas

gapminder |>
  filter(year == 2007 & continent == "Americas") |>
  ggplot(aes(x = reorder(country, pop), y = pop/1000000)) +
  geom_col() +
  coord_flip()

grafico_barras_ggplot2 <-
  gapminder |>
  filter(year == 2007 & continent == "Americas") |>
  ggplot(aes(x = reorder(country, pop), y = pop / 1000000)) +
  geom_col(aes(
    text = paste0(
      "País: ",
      country,
      "\n",
      "Población (millones de habitantes): ",
      round(pop / 1000000, 2)
    )
    
  ))
Warning in geom_col(aes(text = paste0("País: ", country, "\n", "Población
(millones de habitantes): ", : Ignoring unknown aesthetics: text

###Barras aplicadas

diamonds |>
  ggplot(aes(x = cut, fill = clarity)) +
  geom_bar(position = "dodge")

##graficos de dispercion

gapminder |>
  filter(year == 2007) |>
  ggplot(aes(x = gdpPercap, y = lifeExp, color = continent)) +
  geom_point()

##graficos de lineas

covid_general |>
  ggplot(aes(x = fecha, y = value, color = variable)) +
  geom_line(aes(y = positivos, color = "Positivos")) +
  geom_line(aes(y = activos, color = "Activos")) +
  geom_line(aes(y = fallecidos, color = "Fallecidos")) +
  geom_line(aes(y = recuperados, color = "Recuperados")) +
  scale_color_manual(
    "",
    values = c(
      "Positivos" = "blue",
      "Activos" = "red",
      "Fallecidos" = "black",
      "Recuperados" = "green"
    )
  )

#elavore un grafico de lineas que muestre la evolucion en el tiempo de los casos de covid hospitalizados en salon y en UCI

covid_general |>
  ggplot(aes(x = fecha, y = value, color = variable)) +
  geom_line(aes(y = salon, color = "Salon")) +
  geom_line(aes(y = uci, color = "UCI")) +

  scale_color_manual(
    "",
    values = c(
      "Salon" = "blue",
      "UCI" = "red"

    )
  )
Warning: Removed 25 rows containing missing values (`geom_line()`).
Removed 25 rows containing missing values (`geom_line()`).

##graficos de pastel

#|label: pastel-grafico-34

# Crear tabla de frecuencias
tabla_frecuencias_delitos_2022_provincias <- table(delitos_2022$Provincia)

# Convertir la tabla en un data frame
delitos_2022_provincias <- as.data.frame(tabla_frecuencias_delitos_2022_provincias)

# Cambiar nombres de columnas del data frame
delitos_2022_provincias <-
  delitos_2022_provincias |>
  rename(Provincia = Var1, Frecuencia = Freq)

# Calcular porcentajes por provincia
delitos_2022_provincias$Porcentaje <-
  100 * delitos_2022_provincias$Frecuencia / sum(delitos_2022_provincias$Frecuencia)

# Crear gráfico de pastel utilizando ggplot2
grafico_pastel_ggplot2 <-
  delitos_2022_provincias |>
  ggplot(aes(x = "", y = Porcentaje, fill = Provincia)) +
  geom_bar(stat = "identity", width = 1) +
  coord_polar("y", start = 0) +
  theme_void() +
  labs(title = "Porcentaje de delitos cometidos en 2022 por provincia",
    subtitle = "Fuente: OIJ") +
  scale_fill_discrete(name = "Provincia") +
  geom_text(
    aes(label = paste0(round(Porcentaje, 1), "%")),
    position = position_stack(vjust = 0.5),
    color = "white",
    size = 4
  ) 

# Despliegue del gráfico
grafico_pastel_ggplot2